import React, { useEffect, useState } from 'react'
import { Form, Button, Input, Space, Table, Tag, Popconfirm, message, Modal, DatePicker, Radio } from 'antd'
import { getUserList, deleteUser, createUser, updateUser } from '../../api/index'
import moment from 'moment'
import './user.css'
const User = () => {
  // 表格数据
  const [tableData, setTableData] = useState([])
  const [paramsData, setParamsData] = useState({
    page: 1,
    limit: 10,
    name: ''
  })
  const [totalData, setTotalData] = useState(0)
  //弹窗数据
  const [open, setOpen] = useState(false)
  const [confirmLoading, setConfirmLoading] = useState(false)
  const [modalText, setModalText] = useState('Content of the modal')

  //表单数据
  const [form] = Form.useForm()
  const [itemId, setItemId] = useState(0)

  //打开弹窗

  //弹窗确认
  const handleOk = () => {
    console.log(form)
    // 验证表单
    form
      .validateFields()
      .then(values => {
        setConfirmLoading(true)
        console.log(values)
        const dateString = moment(values.birth).format('YYYY-MM-DD')
        let data = {
          name: values.name,
          age: values.age,
          sex: values.sex,
          birth: dateString,
          addr: values.addr
        }
        // 发送请求
        if (itemId != 0) {
          updateUser({
            ...data,
            id: itemId
          }).then(() => {
            setConfirmLoading(false)
            setItemId(0)
            message.success('修改成功')
            getTableData()
            setOpen(false)
          })
        } else {
          createUser(data).then(() => {
            setConfirmLoading(false)
            message.success('添加成功')
            setItemId(0)
            getTableData()
            setOpen(false)
          })
        }
      })
      .catch(err => {
        message.error('请正确填写表单信息')
      })
  }

  //弹窗取消
  const handleCancel = () => {
    console.log('Clicked cancel button')
    setOpen(false)
  }

  const getTableData = () => {
    console.log({
      page: paramsData.page,
      limit: paramsData.limit,
      name: paramsData.name
    })

    getUserList({
      page: paramsData.page,
      limit: paramsData.limit,
      name: paramsData.name
    }).then(({ data }) => {
      const { list } = data
      console.log(data)

      setTotalData(data.count)

      setTableData(list)

      // setTableData(res.data)
    })
  }
  const tableChange = page => {
    console.log(page)
    setParamsData(
      Object.assign(paramsData, {
        page: page.current,
        limit: page.pageSize
      })
    )
    getTableData()
  }
  const onDelete = id => {
    deleteUser({ id }).then(() => {
      message.success('删除成功')
      getTableData()
    })
  }

  useEffect(() => {
    getTableData()
  }, [])
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: text => <a>{text}</a>
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age'
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      render: text => <Tag color={text === 1 ? 'green' : 'geekblue'}>{text === 1 ? '男' : '女'}</Tag>
    },
    {
      title: '出生日期',
      dataIndex: 'birth',
      key: 'birth'
    },
    {
      title: '地址',
      dataIndex: 'addr',
      key: 'addr'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          {/* <a>编辑</a> */}
          <Button onClick={() => handClick('edit', record)}>编辑</Button>

          <Popconfirm title="提示" description="确认删除吗?" onConfirm={() => onDelete(record.id)} okText="确认" cancelText="取消">
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  const handClick = (type, record) => {
    console.log(type, record)
    if (type === 'edit') {
      setModalText('编辑')
      form.setFieldsValue({
        name: record.name,
        age: record.age,
        sex: record.sex,
        birth: moment(record.birth),
        addr: record.addr
      })
      setItemId(record.id)
    }
    if (type === 'add') {
      form.resetFields()
      setModalText('新增')
    }
    setOpen(true)
  }
  const handFinish = e => {
    setParamsData(Object.assign(paramsData, { name: e.keyword }))
    getTableData()
  }

  const onFormFinish = values => {
    console.log(values)
  }
  const onFormFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo)
  }

  return (
    <div className="user">
      <div className="flex-box">
        <Button type="primary" onClick={() => handClick('add')}>
          +新增
        </Button>

        <Form layout="inline" onFinish={handFinish}>
          <Form.Item name="keyword">
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div style={{ marginTop: '20px' }}>
        <Table onChange={tableChange} pagination={{ total: totalData }} columns={columns} rowKey="name" dataSource={tableData} />
      </div>

      <Modal
        title={modalText}
        open={open}
        okText="确认"
        cancelText="取消"
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
        preserve={false}
      >
        {/* <p>{modalText}</p> */}

        <Form
          name="basic"
          labelCol={{
            span: 8
          }}
          form={form}
          wrapperCol={{
            span: 16
          }}
          style={{
            maxWidth: 600
          }}
          initialValues={{
            remember: true
          }}
          autoComplete="off"
        >
          {/* name, addr, age, birth, sex */}
          <Form.Item
            label="姓名"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入姓名'
              }
            ]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item
            label="年龄"
            name="age"
            rules={[
              {
                required: true,
                message: '请输入年龄'
              }
            ]}
          >
            <Input placeholder="请输入年龄" />
          </Form.Item>

          <Form.Item
            label="性别"
            name="sex"
            initialValue={1}
            rules={[
              {
                required: true,
                message: '请选择性别'
              }
            ]}
          >
            <Radio.Group>
              <Radio value={1}>男</Radio>
              <Radio value={0}>女</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="地址"
            name="addr"
            rules={[
              {
                required: true,
                message: '请输入地址'
              }
            ]}
          >
            <Input placeholder="请输入地址" />
          </Form.Item>

          <Form.Item
            label="出生日期"
            name="birth"
            rules={[
              {
                required: true,
                message: '请输入出生日期'
              }
            ]}
          >
            <DatePicker format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" placeholder="请选择出生日期" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default User
